package com.sdl.timesblogmp.controller;

import com.sdl.timesblogmp.model.entity.Admin;
import com.sdl.timesblogmp.model.vo.ApiResult;
import com.sdl.timesblogmp.model.vo.LoginUser;
import com.sdl.timesblogmp.security.JwtService;
import com.sdl.timesblogmp.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
import static com.sdl.timesblogmp.config.ServerConfig.getRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sdl
 * @since 2020-05-11
 */
@Api(value = "用户接口", tags = "用户接口")
@RestController
@RequestMapping("/auth")
public class AdminController {
    @Resource
    private AdminService adminService;
    @Resource
    private JwtService jwtService;

    @ApiOperation(value = "用户登录", response = ApiResult.class)
    @PostMapping("/login")
    public ApiResult login(@RequestBody LoginUser loginUser) {
        System.out.println(loginUser);
        String token = adminService.AdminLogin(loginUser);
        ApiResult apiResult =  ApiResult.success();
        apiResult.put("token",token);
        return apiResult;
    }
    @ApiOperation(value = "更新用户信息")
    @PutMapping("/update")
    public ApiResult updateInfo(@RequestBody Admin admin) {
        int result = adminService.updateAdmin(admin);
        return ApiResult.success();
    }
    @ApiOperation(value = "更改用户密码")
    @PutMapping("/updatepwd")
    public ApiResult updatepassword(@RequestBody Map<String,Object> json) {
        int id = (int) json.get("id");
        String oldpassword = (String) json.get("oldpassword");
        String newpassword = (String) json.get("newpassword");
        adminService.updatepwd(id,oldpassword,newpassword);
        return ApiResult.success();
    }
    @ApiOperation(value = "获取登录用户信息")
    @GetMapping("/getuserinfo")
    public ApiResult getuserinfo() {
        String userName = jwtService.getUserName(jwtService.getToken(getRequest()));
        Admin admin = adminService.findAdminByName(userName);
        return ApiResult.success(admin);
    }
}

